﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YBApproval.Model;
using YBApproval.IDAL;
using YBApproval.BLL;
using YBApproval.Common;
using YBApproval.UserControls;

namespace YBApproval.Pages
{
    public partial class Request : System.Web.UI.Page
    {
        private IInstance _instDAL = DALFactory.GetDAL<IInstance>();
        private IInstanceApproval _instApprovalDAL = DALFactory.GetDAL<IInstanceApproval>();
        private IForm _formDAL = DALFactory.GetDAL<IForm>();
        private INode _nodeDAL = DALFactory.GetDAL<INode>();

        private bool _isNew = true;
        private string _instanceId;
        private int _formId;
        private int _processId;
        private Instance _inst;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _isNew = Convert.ToBoolean(Request.Params["IsNew"]);
                //_formId = Convert.ToInt32(Request.Params["FormId"]);

                if (_isNew)
                {
                    #region New
                    // TODO: get form id from request parameter
                    // Create a new request
                    // 由 List 界面发起，需要传入 FormId，或者 RecordId
                    _formId = Convert.ToInt32(Request.Params["RequestId"]);    // This is code
                    
                    // 如果是新增
                    _instanceId = Guid.NewGuid().ToString();
                    _isNew = true;
                    #endregion
                }
                else
                {
                    #region Update
                    // Get existed request
                    //TODO: 
                    // request 可以被修改，则需要可以从数据库中读取后显示并修改
                    // 由UNForm 控件提供功能，需要传入 instance 的 RecordID 或者 instance 的实例

                    // 如果 instance 是被退回的情况，需要显示审批过程的数据
                    _instanceId = Request.Params["RequestId"].ToString();
                    _inst = GetInstance();
                    _formId = _inst.FormId;
                    // 如果是更新
                    _isNew = false;
                    #endregion
                }
                _processId = _formDAL.GetProcessId(_formId);
            }
            else
            {
                if (ViewState["_isNew"] != null)
                {
                    _isNew = Convert.ToBoolean(ViewState["_isNew"]);
                }
                if (ViewState["_instanceId"] != null)
                {
                    _instanceId = ViewState["_instanceId"].ToString();
                }
                if (ViewState["_formId"] != null)
                {
                    _formId = Convert.ToInt32(ViewState["_formId"]);
                }
                if (ViewState["_processId"] != null)
                {
                    _processId = Convert.ToInt32(ViewState["_processId"]);
                }
            }

            if (_isNew)
            {
                this.UCForm1.FormId = _formId;
            }
            else
            {
                if (_inst == null)
                {
                    _inst = GetInstance();
                }
                this.UCForm1.FormId = _inst.FormId;
                this.UCForm1.RecordId = _inst.RecordId;

                List<InstanceApproval> instApprovalList = _instApprovalDAL.GetInstanceApprovals(_instanceId);
                foreach (InstanceApproval ia in instApprovalList)
                {
                    // this node has been approved or denied
                    if ((ia.IsApproved != false || ia.IsDenied != false) && ia.NodeOrder != _inst.CurrentNodeOrder)
                    {
                        UCApprovalView ucAV = (UCApprovalView)Page.LoadControl("/UserControls/UCApprovalView.ascx");
                        ucAV.ApprovalIns = ia;
                        Panel1.Controls.Add(ucAV);
                    }
                }
            }

            // 该步骤是 设置下一步 的审批人
            // 设置Node的order
            this.Approver1.ProcessId = _processId;
            this.Approver1.NodeOrder = 1;
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            // 将属性保存到ViewState中
            ViewState.Add("_isNew", _isNew);
            ViewState.Add("_instanceId", _instanceId);
            ViewState.Add("_formId", _formId);
            ViewState.Add("_processId", _processId);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(@"~/Default.aspx");
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // TODO: Get instance guid from request parameter
            string errorMsg;


            // instance values
            List<InstanceValue> values = this.UCForm1.GetValues(out errorMsg);
            if (string.IsNullOrEmpty(errorMsg))
            {
                foreach (InstanceValue iv in values)
                {
                    iv.RecordId = _instanceId;
                    iv.Field = null;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "input_validate", "alert('" + errorMsg + "');", true);
                return;
            }



            Instance inst = GetInstance();

            inst.ProcessId = _processId;
            inst.UpdateDate = DateTime.Now;

            // 给instance赋值
            inst.IsSubmitted = true;
            inst.SubmitDate = DateTime.Now;
            inst.Submitter = YBPSession.Instance.CurrentUser.Name;
            inst.SubmitterId = YBPSession.Instance.CurrentUser.Id;

            inst.ClosedBy = "";
            inst.CloseDate = ConstValue.NullDate;
            inst.IsClosed = false;

            //获取下一个节点
            Node nextNode = _nodeDAL.GetCurrentNode(_processId, 1);
            if (nextNode != null)
            {
                //给instance 设置当前node信息
                inst.CurrentNodeId = nextNode.Id;
                inst.CurrentNodeOrder = 1;
                inst.Step += 1;         // 因为int类型肯定会有值，所以这里没有判断
            }




            // instance approvals
            List<InstanceApproval> approvals = _instApprovalDAL.GetInstanceApprovals(inst.FormId, inst.CurrentNodeOrder);
            // 获取用户手工录入的审批人
            List<ApprovalView> approvers = this.Approver1.GetValues();
            for (int i=0; i < approvals.Count; i++)
            {
                approvals[i].RecordId = inst.RecordId;
                approvals[i].ApproverName = "";
                approvals[i].Comment = "";
                approvals[i].ApproveDate = ConstValue.NullDate;
                approvals[i].Step = 1;

                approvals[i].DefaultApproverId = int.Parse(approvers[i].ApproverId);
                approvals[i].DefaultApprover = approvers[i].ApproverName;
                approvals[i].IsRole = approvers[i].IsRole;
            }

            

            // save to db
            try
            {
                if (_isNew)
                {
                    _instDAL.Add(inst, values, approvals);
                }
                else
                {
                    _instDAL.Update(inst, values, approvals, null);
                }

                // 保存成功之后返回List界面
                Response.Redirect(@"~/Default.aspx");
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "input_validate", "alert('" + ex.Message + "');", true);
            }
        }

        private Instance GetInstance()
        {
            Instance instResult = null;
            if (_instanceId != null)
            {
                instResult = _instDAL.GetInstance(_instanceId);
            }

            if (instResult == null)
            {
                _isNew = true;
                instResult = new Instance();
                instResult.RecordId = Guid.NewGuid().ToString();
                instResult.FormId = _formId;
            }
            else
            {
                _isNew = false;
            }
            return instResult;
        }




        /// <summary>
        /// 保存为草稿
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string errorMsg;



            // instance values
            List<InstanceValue> values = this.UCForm1.GetValues(out errorMsg);
            if (string.IsNullOrEmpty(errorMsg))
            {
                foreach (InstanceValue iv in values)
                {
                    iv.RecordId = _instanceId;
                    iv.Field = null;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "input_validate", "alert('" + errorMsg + "');", true);
                return;
            }



            Instance inst = GetInstance();

            inst.ProcessId = _processId;
            inst.UpdateDate = DateTime.Now;


            // 给instance赋值
            inst.IsSubmitted = false;
            inst.SubmitDate = DateTime.Now;
            inst.Submitter = YBPSession.Instance.CurrentUser.Name;
            inst.SubmitterId = YBPSession.Instance.CurrentUser.Id;

            inst.ClosedBy = "";
            inst.CloseDate = ConstValue.NullDate;
            inst.IsClosed = false;

            //获取下一个节点
            Node nextNode = _nodeDAL.GetCurrentNode(_processId, 1);
            if (nextNode != null)
            {
                //给instance 设置当前node信息
                inst.CurrentNodeId = nextNode.Id;
                inst.CurrentNodeOrder = 1;
                inst.Step += 1;         // 因为int类型肯定会有值，所以这里没有判断
            }


            




            // save to db
            try
            {
                if (_isNew)
                {
                    _instDAL.Add(inst, values);
                }
                else
                {
                    _instDAL.Update(inst, values);
                }

                // 保存成功之后返回List界面
                Response.Redirect(@"~/Default.aspx");
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "input_validate", "alert('" + ex.Message + "');", true);
            }
        }

    }
}